package com.xinyue.game.dataconfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;

/**
 * @Author 王广帅
 * @Date 2021/5/9 22:40
 */
public class GameDataConfigService {
    private Logger logger = LoggerFactory.getLogger(GameDataConfigService.class);
    private Map<String, GameDataConfigManager> dataConfigCacheMap = new HashMap<>();

    public void addDataConfig(Class<?> clazz, String id, Object dataConfig) {
        String key = getCacheKey(clazz);
        GameDataConfigManager gameDataConfigManager = dataConfigCacheMap.computeIfAbsent(key, k -> new GameDataConfigManager());
        gameDataConfigManager.addDataConfig(id, dataConfig);
    }

    private String getCacheKey(Class<?> clazz) {
        return clazz.getName();
    }

    public <T> Optional<T> getDataConfig(String id, Class<T> clazz) {
        String key = getCacheKey(clazz);
        GameDataConfigManager<T> gameDataConfigManager = this.dataConfigCacheMap.get(key);
        assert gameDataConfigManager == null : "配置表" + clazz.getName() + "未加载到数据";
        return gameDataConfigManager.getDataConfig(id);
    }

    public <T> Collection<T> getAllDataConfigList(Class<T> clazz) {
        String key = getCacheKey(clazz);
        GameDataConfigManager<T> gameDataConfigManager = this.dataConfigCacheMap.get(key);
        return gameDataConfigManager.getAllDataConfigList();
    }

    public <T> Collection<T> getDataConfigList(Class<T> clazz, Predicate<T> filter) {
        String key = getCacheKey(clazz);
        GameDataConfigManager<T> gameDataConfigManager = this.dataConfigCacheMap.get(key);
        return gameDataConfigManager.getDataConfigList(filter);
    }

    /**
     * 将集合变为不可变。当所有的配置数据都加载完成之后，调用这个方法，这样可以防止在开发
     * 游戏业务逻辑的时候开发人员误操作修改配置数据
     */
    public void unmodifiableConfigData() {
        this.dataConfigCacheMap.values().forEach(gameDataConfigManager -> gameDataConfigManager.unmodifiableConfigData());
    }
}
